<template>
  <div class="login-container">
    <el-card class="box-card login">
      <div slot="header" class="clearfix">
        <span>请登录账号</span>
      </div>
      <div>
        <!-- 登录的表单 -->
        <el-form
          label-width="80px"
          :model="loginForm"
          :rules="loginFormRules"
          ref="loginFormRef"
        >
          <el-form-item label="账号" prop="username">
            <el-input v-model="loginForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="loginForm.password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="isLoading"
              type="primary"
              @click="handleLogin('loginFormRef')"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";
import { Message } from "element-ui";
export default {
  data() {
    return {
      isLoading: false,
      loginForm: {
        username: "admin",
        password: "123456",
      },
      loginFormRules: {
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    handleLogin(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 开启登录的加载效果
          this.isLoading = true;
          // alert("submit!");
          // console.log(this.loginForm);
          // 1. 发送网络请求
          axios
            .post(
              "https://www.fastmock.site/mock/c1a29450dae2986f65503ce0402c5b29/admin/api/login",
              this.loginForm
            )
            .then((res) => {
              // Message.success("登录成功");
              console.log(res);
              // 2. 如果登录成功把 token（成功的标识）存到本地存储中
              localStorage.setItem("token", res.data.message.token);

              // 3. 跳转到首页
              this.$router.push("/");
              // 关闭登录的loading 效果
              this.isLoading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.login-container {
  .login {
    width: 25rem;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
